package cn.itcast.service.cargo.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.itcast.dao.cargo.*;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.vo.ExportProductResult;
import cn.itcast.domain.vo.ExportProductVo;
import cn.itcast.domain.vo.ExportResult;
import cn.itcast.domain.vo.ExportVo;
import cn.itcast.service.cargo.ExportService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class ExportServiceImpl implements ExportService {

    @Autowired
    private ExportDao exportDao; // 报运dao

    @Autowired
    private ExportProductDao exportProductDao;//报运单商品dao

    @Autowired
    private ExtEproductDao extEproductDao;  //报运单附件Dao

    @Autowired
    private ContractDao contractDao; // 合同dao

    @Autowired
    private ContractProductDao contractProductDao; //合同货物dao

    @Autowired
    private ExtCproductDao extCproductDao;  //合同附件Dao

    //保存

    public void save(Export export) {
//0  草稿
        //1 已上报
        //2  已报运
        //保存到报运单数据库并修改合同状态
            export.setId(IdUtil.simpleUUID());
            String[] contractArray = export.getContractIds().split(",");
            ContractExample contractExample = new ContractExample();
            contractExample.createCriteria().andIdIn(Arrays.asList(contractArray));
            List<Contract> contractList = contractDao.selectByExample(contractExample);
            String customerContract = "";
            Integer proNum = 0;
            Integer extNum = 0;
            for (Contract contract : contractList) {
                customerContract += contract.getContractNo() + " ";

                proNum += contract.getProNum();
                extNum += contract.getExtNum();
                contract.setState(2);
                contractDao.updateByPrimaryKeySelective(contract);
            }
            export.setCustomerContract(customerContract);
            export.setProNum(proNum);
            export.setExtNum(extNum);
            export.setState(0);
            exportDao.insertSelective(export);
            // 将所有合同的货物对象封装到 报运单商品对象 （一对一）
            ContractProductExample cpExample = new ContractProductExample();
            cpExample.createCriteria().andContractIdIn(Arrays.asList(contractArray));
            List<ContractProduct> cpList = contractProductDao.selectByExample(cpExample);
            for (ContractProduct cp : cpList) {
                ExportProduct ep = new ExportProduct();
                BeanUtil.copyProperties(cp, ep);
                ep.setId(IdUtil.simpleUUID());
                ep.setExportId(export.getId());
                exportProductDao.insertSelective(ep);
                // 将所有合同附件对象封装到 报运单附件对象 （一对一）
                ExtCproductExample extcExample = new ExtCproductExample();
                extcExample.createCriteria().andContractProductIdEqualTo(cp.getId());
                List<ExtCproduct> extcList = extCproductDao.selectByExample(extcExample);
                for (ExtCproduct extc : extcList) {
                    ExtEproduct exte = new ExtEproduct();
                    BeanUtil.copyProperties(extc, exte);
                    exte.setId(IdUtil.simpleUUID());
                    exte.setExportId(export.getId());
                    exte.setExportProductId(ep.getId());
                    extEproductDao.insertSelective(exte);
                }
            }

        }

    //更新
    public void update(Export export) {
        exportDao.updateByPrimaryKeySelective(export);
        List<ExportProduct> list = export.getExportProducts();
        if (list!=null&&list.size()>0) {
            for (ExportProduct ep : list) {
                exportProductDao.updateByPrimaryKeySelective(ep);
            }
        }
    }

    //删除
    public void delete(String id) {
        //先通过id查找附件
        ExtEproductExample exteExample = new ExtEproductExample();
        ExtEproductExample.Criteria criteria = exteExample.createCriteria();
        criteria.andExportIdEqualTo(id);
        List<ExtEproduct> extEproducts = extEproductDao.selectByExample(exteExample);
        for (ExtEproduct extEproduct : extEproducts) {
            //删除附件
            extEproductDao.deleteByPrimaryKey(extEproduct.getId());
        }
        //再通过ID查找商品
        ExportProductExample epExample = new ExportProductExample();
        ExportProductExample.Criteria epCriteria = epExample.createCriteria();
        epCriteria.andExportIdEqualTo(id);
        List<ExportProduct> exportProducts = exportProductDao.selectByExample(epExample);
        //删除商品
        for (ExportProduct exportProduct : exportProducts) {
            exportProductDao.deleteByPrimaryKey(exportProduct.getId());
        }
        //删除报运单
        exportDao.deleteByPrimaryKey(id);

    }

    //根据id查询
    public Export findById(String id) {
        return exportDao.selectByPrimaryKey(id);
    }

    //分页
    public PageInfo findByPage(int pageNum, int pageSize, ExportExample example) {
        PageHelper.startPage(pageNum, pageSize);
        List<Export> list = exportDao.selectByExample(example);
        return new PageInfo(list);
    }
	
	public List<Export> findAll(ExportExample example){
		return exportDao.selectByExample(example);
	}
    @Override
    public void exportE(String id) {
        // 1.根据id查询报运单对象
        Export export = exportDao.selectByPrimaryKey(id);

        // 2.根据报运单id查询商品列表
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> epList = exportProductDao.selectByExample(exportProductExample);

        // 3.将export对象封装到exportVo对象
        ExportVo exportVo = new ExportVo();
        BeanUtil.copyProperties(export, exportVo);
        exportVo.setExportId(export.getId()); // 报运单id

        // 4.将export商品对象封装到exportProductVo对象中
        List<ExportProductVo> epvList = new ArrayList<>();
        for (ExportProduct ep : epList) {
            ExportProductVo epv = new ExportProductVo(); // 海关商品标准对象
            BeanUtil.copyProperties(ep, epv);
            epv.setEid(export.getId()); // 报运单id
            epv.setExportProductId(ep.getId()); // 商品id

            epvList.add(epv);

        }
        exportVo.setProducts(epvList);

        // 5.使用ws的客户端发送电子报运
        WebClient sendExportVo = WebClient.create("http://localhost:8088/ws/export/user");
        sendExportVo.post(exportVo);

        // 6.修改报运单状态
        export.setState(2); // 已上报
        exportDao.updateByPrimaryKeySelective(export);
    }

    public void changeExportEResult(String id) {
        // 1.调用ws客户端根据报运单id查询报运结果
        WebClient findExportResult = WebClient.create("http://localhost:8888/ws/export/user/" + id);
        ExportResult exportResult = findExportResult.get(ExportResult.class);
        // 2.同步到数据库
        if (exportResult != null) {
            // 3.同步报运单
            Export export = new Export();
            export.setId(exportResult.getExportId());
            export.setState(exportResult.getState()); // 报运单状态
            //  export.setRemark(exportResult.getRemark()); //  海关的审核说明
            exportDao.updateByPrimaryKeySelective(export);
            //  4.同步报运单商品
            Set<ExportProductResult> products = exportResult.getProducts();
            if (CollectionUtil.isNotEmpty(products)) {
                for (ExportProductResult product : products) {
                    ExportProduct exportProduct = new ExportProduct();
                    exportProduct.setId(product.getExportProductId()); // 商品id
                    exportProduct.setTax(product.getTax()); // 商品含税价
                    exportProductDao.updateByPrimaryKeySelective(exportProduct);
                }
            }
        }
    }
}
